<?php
 class Payment extends CS_Controller{
 	
     public function _init(){
         $this->load->helper(array('common','validation', 'line'));
         $this->load->library('alipay/alipaypc', null, 'alipaypc');
         $this->load->model('line_base_model', 'line_base');
         $this->load->model('sales_order_model', 'sales_order');
         $this->load->model('line_order_product_model', 'line_order_product');
         $this->load->model('pay_failure_log_model', 'pay_failure_log');
         $this->load->model('user_model', 'user');
         $this->load->model('user_account_model', 'user_account');
         $this->load->model('account_log_model', 'account_log');
         $this->load->model('pay_method_model', 'pay_method');
         $this->load->model('user_model','user');
     }
     
     public function toPayOrderLine($order_sn){
     	
         $order_info = $this->sales_order->byOrderOrderSn($order_sn);
         if ($order_info->num_rows() <= 0) {
             $this->alertJumpPre('订单信息有误。');
         }
         $orderInfo = $order_info->row();
         $data['order_info'] = $orderInfo;
         $data['name'] = '支付信息';
         $data['back_url'] = '';
         $data['wx_status'] = validateWeiXin();
         $this->load->view('line/payment/payment',$data);
     }
     
    public function orderToPay(){

        $order_id = $this->input->get('order_id');
        $pay_bank =  $this->input->get('pay_bank');
        $pay_from = '2';    // 1代表pc端支付   2代表移动端支付
        $result = $this->sales_order->findByOrderIdInfo($order_id);  //3表示线路订单
        if ($result->num_rows() <= 0) {
            $this->alertJumpPre('订单信息不对。');
        }
        $orderInfo = $result->row();
        $order_sn  = $orderInfo->order_sn;
        $update    = $this->sales_order->updatePayBank($pay_bank,$pay_from,$order_id); //更新支付方式
        switch ($pay_bank) {
        	case '99' :     //余额支付
        	    $userAccount = $this->user_account->findByUid($this->uid);
        	    $data['userAccount'] = $userAccount->row();
        	    $data['orderInfo']   = $orderInfo;
        	    $data['name'] = '着想支付';
        	    $data['back_url'] = 'line/payment/toPayOrderLine/'.$order_sn;
        	    $this->load->view('line/payment/balancePay',$data);
        	    break;
        	case '201':    //微信支付
        	    $url = $this->config->wap_base_url."js_call.php?order_id=".$order_id;
        	    header("Location:$url");
        	    break;
        	case '1':      //支付宝支付
        	    $alipayParameter = $this->alipayParameter($pay_bank,$orderInfo);
        	    $this->alipaypc->callAlipayApi($alipayParameter);
        	    break;
        }
    }

    /**
     * 获取支付宝,微信支付需要参数。
     * @param paybank $bank_id
     * @param object $orderInfo
     * @param object $orderProductInfo
     * @return array
     */
    private function alipayParameter($pay_bank,$orderInfo)
    {
        $parameter = array(
                'out_trade_no' => $orderInfo->order_sn,
                'subject'      => $orderInfo->line_name,
                'total_fee'    => $orderInfo->order_pay_total,
                'body'         => $orderInfo->line_name,
                'notify_url'   => site_url('line/paycallback/alipayNotify'),
                'call_back_url'=> site_url('line/payment/alipayReturn'),
                'show_url'     => site_url('line/lineproduct/view/'.$orderInfo->line_id),
                'pay_method'   => $pay_bank
        );
        $payBankCode = $this->pay_method->findByBankId($pay_bank);
        $parameter['defaultbank'] = $payBankCode->bank_code;
        return $parameter;
    }
    
    /**
     * 支付宝支付回调函数。
     */
    public function alipayReturn()
    {
        $response = $this->alipaypc->responseAlipayReturn();
        $order_sn = $this->input->get('out_trade_no');
        $getDate = $this->input->get();
        $result = $this->sales_order->byOrderOrderSn($order_sn);
        $orderInfo = $result->row();
        if ($response) { //$response付款成功；判断第二次执行, 表示未付款
            if ($orderInfo->order_state != 2) {
                $is_update = $this->sales_order->payUpdateOrderStatus($order_sn); //支付成功，修改状态
            }
            $this->session->set_userdata('last_order_id', $orderInfo->order_id); //将订单id保存在session中。
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_sn, $getDate, $response);
            }
        }
        $this->redirect('line/payment/completePay');
    }
    
    /**
     * 下完订单后的跳转方法
     * 短线，去付款的界面
     */
    public function payOrderLine()
    {
        $last_order_id = $this->session->userdata('last_order_id');
        $order_info = $this->sales_order->findByOrderIdInfo($last_order_id);
        if ($order_info->num_rows() <= 0) {
            $this->alertError('此订单不合法，或者不存在。');
        }
        $data['name'] = '支付信息';
        $data['back_url'] = '';
        $data['order_info']  = $order_info->row();
		$data['wx_status'] = validateWeiXin();
        $this->load->view('line/payment/payment', $data);
    }

    /**
     * 到付或者长线的跳转页面
     * 下单成功。
     */
    public function placeAnOrder()
    {
        $last_order_id = $this->session->userdata('last_order_id');
        $order_info = $this->sales_order->findByOrderIdInfo($last_order_id);
        if ($order_info->num_rows() <= 0) {
            $this->alertError('此订单不合法，或者不存在。');
        }
        $order_info           = $order_info->row();
        $data['order_info']   = $order_info;
        $data['order_detail'] = site_url('line/lineorder/line_order_detail').'?order_id='.$order_info->order_id.'&order_status='.$order_info->order_status;
        $data['name'] = '预订成功';
        $data['back_url'] = '';
        if ($this->validateUserType()) {
            $data['order_detail'] = site_url('line/lineorder/line_order_detail').'?order_id='.$order_info->order_id.'&order_status='.$order_info->order_status;
        }
        $this->load->view('line/payment/completePay', $data);
    }
    
    /**
     * 余额支付过程
     */
    public function balancePayForm()
    {
        $uid = $this->uid;
        $password = $this->input->post('password');
        $order_id = $this->input->post('order_id');
        $this->db->trans_start();
        $resultUser = $this->user->validateAccountPassword($uid, $password);
        if ($resultUser->num_rows() <= 0) {
            $this->alertJumpPre('支付密码填写错误！');
        }
        $userAccount = $resultUser->row();
        $resultOrder = $this->sales_order->findByOrderIdInfo($order_id); //3表示线路订单
        if ($resultOrder->num_rows() <= 0) {
            $this->alertJumpPre('订单信息不对。');
        }
        $orderInfo = $resultOrder->row();
        //验证账户余额是否大于当前订单金额。
        if ($userAccount->amount_carry < $orderInfo->order_pay_total) {
            $this->alertJumpPre('当前余额不足支付订单。');
        }
        //查看订单是否已支付    支付成功就跳转支付成功页面
        $is_repeat = $this->sales_order->findByStatus($order_id, 2, 4);
        if ($is_repeat->num_rows() > 0) {
            $this->redirect('line/payment/completePay');
        }
        $amount_carry = (int)$userAccount->amount_carry - (int)$orderInfo->order_pay_total;
        $updateAmountCarry = $this->user_account->updateAmountCarry($uid, $amount_carry);
        if (!$updateAmountCarry) {
             $this->alertJumpPre('余额支付失败。');
        }
        $is_update = $this->sales_order->payUpdateOrderStatus($orderInfo->order_sn); //支付成功，修改订单状态
        if ($is_update) {
            $this->account_log->insertAccountLogUser($order_id, $uid, $orderInfo->order_pay_total, $amount_carry, 1); //1表示支付
            $this->session->set_userdata('last_order_id', $order_id); //将订单id保存在session中。
        }

        $this->db->trans_complete();
        $this->redirect('line/payment/completePay');
    }
    
    /**
     * 余额付完款之后，支付完成的跳转方法。
    */
    public function completePay()
    {
        $last_order_id = $this->session->userdata('last_order_id');
        $this->completePayCommon($last_order_id,$sms=false);
    }
    
    /**
     * 微信支付成功  完成的跳转方法（同步跳转）
     * @param unknown $last_order_id
     */
    public function wxCompletePay($last_order_id){

        $this->completePayCommon($last_order_id,$sms=true);
    }
    
    public function completePayCommon($last_order_id, $sms)
    {
        $order_info = $this->sales_order->findByOrderIdInfo($last_order_id);
        if ($order_info->num_rows() <= 0) {
            $this->alertError('此订单不合法，或者不存在。');
        }
        $order_info  = $order_info->row();

        $data['order_info']   = $order_info;
        $data['order_detail'] = site_url('line/lineorder/line_order_detail?order_id='.$order_info->order_id.'&order_status='.$order_info->order_status);
        if ( $this->validateUserType() ) { //如果为分销商
            $data['order_detail'] = site_url('line/lineorder/line_order_detail?order_id='.$order_info->order_id.'&order_status='.$order_info->order_status);
        }
        //如果是到付( 订单状态大于1，并且$order_info->pay_style_type不等于1)
        //或者是在线支付（订单状态大于1，并且$order_info->pay_style_type不等于1）成功
        $data['back_url'] = '';
        if ($order_info->order_state == 2) {
            $data['name'] = '预订成功';
            $this->load->view('line/payment/completePay',$data);
        } else {
            
            $data['name'] = '预订失败';
            $data['payEwmName'] = $this->payEwm($last_order_id);
            $data['wx_status'] = validateWeiXin();
            $this->load->view('line/payment/problemPay',$data);
        }
    }
    
    /**
     * 检验支付密码
     */
    public function checkPayPassword()
    {
        $uid = $this->uid;
        $password = $this->input->get('password');
        $resultUser = $this->user->validateAccountPassword($uid, $password);
        if ($resultUser->num_rows() > 0) {
             echo 'true';exit;
        }else{
        	 echo 'false';exit;
        }
    }
    
   /**
     * 付款二维码生成
     * @param unknown $order_id
     * @return string
     */
    public function payEwm($order_id)
    {
        $name = 'payEwm'.$order_id;
        $url = $this->config->wap_base_url."js_call.php?order_id=".$order_id;
        $path = $this->config->upload_image_path('m/line',$name.'.png');
        if( !is_dir($this->config->upload_image_path('m/line')) ) {
            mkdir($this->config->upload_image_path('m/line'),DIR_WRITE_MODE,true);
        }
        $data = array(
            'url'                  => $url, //二维码内容
            'errorCorrectionLevel' => 'L', //容错级别
            'matrixPointSize'      => 6, //生成图片大小
            'QR'                   => $this->config->upload_image_path('line', $name.'.png'),
            'logo'                 => $this->config->upload_image_path('common/ewm', 'logo_30.png'), //准备好的logo图片
            'output'               => $path
        );
        $this->load->library('qrcode/qr_code', null, 'qr_code');
        $this->qr_code->generate($data);
        $data['name'] = $name.'.png';
        return $data['name'];
    }
}
